package com.linzm.model;

import com.linzm.utils.HttpProtocolUtil;
import com.linzm.utils.StaticResourceUtil;
import lombok.SneakyThrows;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;

/**
 * 封装Response对象，需要依赖于OutputStream
 *
 * @Date: 2023/11/6 22:49
 * @User linziming
 */
public class Response {
    private OutputStream outputStream;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public Response() {
    }

    @SneakyThrows
    public void outputHtml(String path) {
        //获取静态资源的绝对路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);

        //输出静态资源文件
        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()) {
            //读取静态资源文件，输出静态资源
            StaticResourceUtil.outputStaticResource(Files.newInputStream(file.toPath()), outputStream);
        } else {
            //输出404
            output(HttpProtocolUtil.getHttpHeader404());
        }
    }

    //使用输出流输出指定字符串
    public void output(String context) throws IOException {
        outputStream.write(context.getBytes());
    }
}
